import java.util.Scanner;
/**
 * @author yu
 * @date 2025年04月19日 16:28
 */


/*// 定义链表节点类
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}*/

public class _02_LinkedList_04_24swapPairs {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode cur = dummy;
        while (cur.next != null && cur.next.next != null) {
            ListNode node1 = cur.next;// 第 1 个节点
            ListNode node2 = cur.next.next;// 第 2 个节点
            cur.next = node2; // 步骤 1
            node1.next = node2.next;// 步骤 2
            node2.next = node1;// 步骤 3
            cur = cur.next.next;
        }
        return dummy.next;
    }

    // 根据用户输入的数组创建链表
    public ListNode createLinkedList(int[] arr) {
        if (arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode(arr[0]);
        ListNode current = head;
        for (int i = 1; i < arr.length; i++) {
            current.next = new ListNode(arr[i]);
            current = current.next;
        }
        return head;
    }

    // 打印链表
    public void printLinkedList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        _02_LinkedList_04_24swapPairs solution = new _02_LinkedList_04_24swapPairs();
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入链表节点的值，用空格分隔：");
        String input = scanner.nextLine();
        String[] valuesStr = input.split(" ");
        int[] values = new int[valuesStr.length];
        for (int i = 0; i < valuesStr.length; i++) {
            values[i] = Integer.parseInt(valuesStr[i]);
        }

        ListNode head = solution.createLinkedList(values);

        System.out.println("原始链表：");
        solution.printLinkedList(head);

        ListNode swappedHead = solution.swapPairs(head);

        System.out.println("两两交换后的链表：");
        solution.printLinkedList(swappedHead);

        scanner.close();
    }
}
